package rwi.informationsystem.internal.is;

import java.util.ArrayList;

import rwi.informationsystem.core.interfaces.IInformationSystem;

public class RWI_ObjectStore implements IInformationSystem {

	ArrayList<RWI_Object> objl;
	private int idcounter;

	protected void startup() {
		idcounter = 0;
		objl = new ArrayList<>();
		System.out.println("Store started");
	}

	protected void shutdown() {
		System.out.println("Store quit");
	}

	private int generateID(){
		return idcounter++;
	}
	@Override
	public synchronized int registerRWI_Object(int type, int posX, int posY) {
		int id = generateID();
		objl.add(new RWI_Object(id, posX, posY));
		return id;
	}

	@Override
	public synchronized void updateRWIObjectPos(int id, int posX, int posY) {
		objl.get(id).updatePosition(posX, posY);
	}

	@Override
	public synchronized void unregisterRWI_Object(int id) {
		RWI_Object rwi = findRwiObjectById(id);
		if (rwi != null) {
			objl.remove(rwi);
		}
	}

	@Override
	public String getIds() {
		return displayRwiObjects();
		// String s = "";
		// if (objl.size() == 0) {
		// return "no objects registered";
		// }
		// for (RWI_Object rwi : objl) {
		// s += rwi.getId() + "(" + rwi.getPosX() + "|" + rwi.getPosY() + ") ";
		// }
		// return s;
	}

	private RWI_Object findRwiObjectById(int id) {
		for (RWI_Object rwi : objl) {
			if (rwi.getId() == id)
				return rwi;
		}
		return null;
	}

	private String displayRwiObjects() {
		String html = "<html><style type='text/css'>.obj{position:absolute;display:block;background-color:#000;color:#FFF;}</style>";
		html += "<div style='width:500px;height:500px;margin:50px;background-color:#DDD;position:absolute;'>";
		for (RWI_Object r : objl) {
			html += "<div class='obj' style='bottom:" + r.getPosY() + ";left:"
					+ r.getPosX() + "' >";
			html += r.getId();
			html += "</div>";
		}
		html += "</div></html>";
		html.replace("'", "\"");
		return html;
	}

	@Override
	public String calculateRoute(int id, int targetPosX, int targetPosY) {
		String s = "";
		for (int x = 0; x < 10000; x++) {
			for (int y = 0; y < 4; y++) {
				s+="-";
			}
		}
		return s;
	}

	@Override
	public void changeRWIObjectState(int id, int state) {
		RWI_Object rwi = findRwiObjectById(id);
		if (rwi.getClass().equals(RWI_Static.class)) {
			RWI_Static s = (RWI_Static) rwi;
			s.setState(state);
		}
	}

}
